﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Mail;
using System.Web.Security;
using System.Collections;
using WebshopPizzaRio.App_Code.DAL;
using System.Data;

namespace WebshopPizzaRio
{
    public partial class Mailing : System.Web.UI.Page
    {
        private NieuwsbriefBLL nbbll = new NieuwsbriefBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            MembershipUser currentuserid = Membership.GetUser();
            
            try
            {
                if ((Guid)currentuserid.ProviderUserKey == null)
                {
                    throw new NullReferenceException();
                }
                else if (!Roles.IsUserInRole("Administrators"))
                {
                    Response.Redirect("Voorpagina.aspx");
                }
            }
            catch (NullReferenceException)
            {
                Response.Redirect("Voorpagina.aspx");
            }
        }

        protected void SendEmail_Click(object sender, EventArgs e)
        {
            Label2.Visible = true;

            String inhoudmail = inhoud.Text;
            String subject = onderwerp.Text;

            String from = "infopizzario@gmail.com";

          
            Nieuwsbriefsubs.nieuwsbriefsubsDataTable to = nbbll.getEmails();

            foreach(Nieuwsbriefsubs.nieuwsbriefsubsRow d in to)
            {
                System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage(from, d.email, subject, inhoudmail);
                MyMailMessage.IsBodyHtml = false;

                // Mail gegevens
                System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential("infopizzario@gmail.com", "Testing123");
                System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);

                // SSL en authenticatie
                mailClient.EnableSsl = true;
                mailClient.UseDefaultCredentials = false;
                mailClient.Credentials = mailAuthentication;
                mailClient.Send(MyMailMessage);
            }
        }
    }
}

